package com.dropdb.demo.shiro;

import com.dropdb.demo.bean.Admin;
import com.dropdb.demo.bean.AdminExample;
import com.dropdb.demo.mapper.AdminMapper;
import com.dropdb.demo.mapper.PermissionMapper;
import com.dropdb.demo.mapper.RoleMapper;
import lombok.SneakyThrows;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class AdminRealm extends AuthorizingRealm {

    @Autowired
    AdminMapper adminMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    PermissionMapper permissionMapper;

    /**
     * 后台认证
     */
    @SneakyThrows
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        // 根据用户名获取用户信息
        AdminExample adminExample = new AdminExample();
        adminExample.createCriteria().andUsernameEqualTo(token.getUsername());
        List<Admin> admins = adminMapper.selectByExample(adminExample);
        if (admins == null || admins.size() == 0) throw new AuthenticationException();
        // 当出现多条相同username账户时，不能简单的返回第一条，抛出异常
        if (admins.size() > 1) throw new RuntimeException("存在同名用户");
        Admin admin = admins.get(0);
        //ByteSource s = new SecureRandomNumberGenerator().nextBytes();
        ByteSource salt=ByteSource.Util.bytes(admin.getUsername());
        return new SimpleAuthenticationInfo(admin, admin.getPassword(),salt, this.getName());
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Admin admin = (Admin) principalCollection.getPrimaryPrincipal();
        List<String> roles = roleMapper.selectRoleNameByRoleId(admin.getRoleIds());
        List<String> perms = permissionMapper.selectPermsNameByRoleId(admin.getRoleIds());
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRoles(roles);
        authorizationInfo.addStringPermissions(perms);
        return authorizationInfo;
    }


}
